import type { UseFetchOptions, AsyncData } from 'nuxt/app'

type Methods = 'GET' | 'POST'
const BASE_URL = 'http://codercba.com:9060/juanpi/api'

export interface IResultData<T> {
	code: number
	data: T
}

class HYRequst {
	request<T = any>(
		url: string,
		methods: Methods,
		data?: any,
		options?: UseFetchOptions<T>
	): Promise<AsyncData<T, Error>> {
		return new Promise((resolve, reject) => {
			const newOptions: UseFetchOptions<T> = {
				baseURL: BASE_URL,
				method: methods,
				...options,
			}

			if (methods === 'GET') {
				newOptions.query = data
			}

			if (methods === 'POST') {
				newOptions.body = data
			}

			useFetch<T>(url, newOptions as any)
				.then((res) => {
					resolve(res as AsyncData<T, Error>)
				})
				.catch((error) => {
					reject(error)
				})
		})
	}

	get<T = any>(url: string, params?: any, options?: UseFetchOptions<T>) {
		return this.request(url, 'GET', params, options)
	}

	post<T = any>(url: string, data?: any, options?: UseFetchOptions<T>) {
		return this.request(url, 'POST', data, options)
	}
}

export default new HYRequst()
